<template>
  <div class="chat-container">
    <div class="chat-header">
      家庭医生 <span v-if="currentUserName">正在和<strong class="user-name">{{ currentUserName }}</strong>沟通中</span>
      <div class="theme-selector">
        <button class="theme-button" @click="toggleThemeMenu">切换主题</button>
        <div class="theme-menu" v-if="showThemeMenu">
          <div v-for="(theme, index) in themes" :key="index" class="theme-item" @click="selectTheme(theme)">
            {{ theme.name }}
          </div>
        </div>
      </div>
      <div class="user-input-container" v-if="!currentUserName">
        <input type="text" v-model="userName" placeholder="输入用户名" class="user-input-field" @keyup.enter="submitUserName"/>
        <button class="submit-button" @click="submitUserName">连接</button>
      </div>
    </div>
    <div class="chat-messages" ref="chatMessages">
      <div v-for="(item, index) in chatList" :key="index" :class="['message', item.chatType === 'user' ? 'user' : 'bot']">
        <div v-if="item.chatType === 'user'" class="user-avatar">{{ currentUserName?.charAt(0) }}</div>
        <div v-if="item.chatType === 'bot'" class="avatar">医生</div>
        <div class="text" v-html="item.content"></div>
      </div>
    </div>
    <div class="chat-input" v-if="currentUserName">
      <textarea
        v-model="userInput"
        placeholder="请输入内容"
        @keydown.enter.prevent="handleEnterPress"
        @input="adjustTextareaHeight"
        ref="messageInput"
        class="message-textarea"
      ></textarea>
      <button @click="doChat">发送</button>
    </div>
  </div>
</template>

<script>
import { doctorApi } from '@/api/doctor'

export default {
  name: 'ChatWithDoctor',
  data() {
    return {
      botMsgId: null,
      currentUserName: null,
      chatList: [],
      userName: '',
      userInput: '',
      showThemeMenu: false,
      currentTheme: null,
      themes: [
        { name: '默认主题', gradient: 'linear-gradient(120deg, #a1c4fd, #c2e9fb)' },
        { name: '薄荷绿', gradient: 'linear-gradient(120deg, #84fab0, #8fd3f4)' },
        { name: '薄荷绿', gradient: 'linear-gradient(120deg, #84fab0, #8fd3f4)' },
        { name: '暖阳橙', gradient: 'linear-gradient(120deg, #fad0c4, #ffd1ff)' },
        { name: '紫罗兰', gradient: 'linear-gradient(120deg, #e0c3fc, #8ec5fc)' }
      ]
    }
  },
  mounted() {
    this.scrollToBottom()
    // 设置默认主题
    this.currentTheme = this.themes[0]
  },
  methods: {
    initSSE(userName) {
      if (!window.EventSource) {
        console.log("浏览器不支持SSE")
        return
      }

      const source = new EventSource(`http://localhost:8443/sse/connect?userId=${userName}`)
      console.log("连接用户=", userName)
      this.currentUserName = userName

      source.addEventListener('open', () => {
        console.log("建立连接...")
      })

      source.addEventListener('add', (e) => {
        console.log("add事件...", e.data)
        const receiveMsg = e.data

        if (!this.botMsgId) {
          this.botMsgId = this.generateRandomId(12)
          const newBotContent = {
            id: "temp",
            content: receiveMsg,
            userName: '家庭医生',
            chatType: 'bot',
            botMsgId: this.botMsgId
          }
          this.chatList.push(newBotContent)
        } else {
          const chatItem = this.chatList.find(item => item.botMsgId === this.botMsgId)
          if (chatItem) {
            chatItem.content += receiveMsg
          }
        }

        this.$nextTick(() => {
          this.scrollToBottom()
        })
      })

      source.addEventListener('finish', () => {
        console.log("finish事件...")
        this.botMsgId = null
        this.scrollToBottom()
      })

      source.addEventListener('error', (e) => {
        console.log("error事件...", e)
        if (e.readyState === EventSource.CLOSED) {
          console.log('connection is closed')
        }
        source.close()
      })
    },

    submitUserName() {
      if (!this.userName.trim()) {
        alert('请输入沟通用户名')
        return
      }
      this.initSSE(this.userName)
      this.getChatRecords(this.userName)
    },

    async getChatRecords(userName) {
      try {
        const result = await doctorApi.getRecords(userName)
        this.chatList = result
        this.$nextTick(() => {
          this.scrollToBottom()
        })
      } catch (err) {
        console.error('获取聊天记录失败:', err)
      }
    },

    doChat() {
      const pendingMsg = this.userInput.trim()
      if (!pendingMsg) return

      if (!this.currentUserName) {
        alert('请输入沟通用户名')
        return
      }

      const singleChat = {
        currentUserName: this.currentUserName,
        message: pendingMsg
      }

      doctorApi.doChat(singleChat)

      this.chatList.push({
        content: pendingMsg,
        userName: this.currentUserName,
        chatType: 'user'
      })

      this.userInput = ''
      this.$nextTick(() => {
        this.scrollToBottom()
      })
    },

    generateRandomId(length) {
      const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
      let result = ''
      for (let i = 0; i < length; i++) {
        result += characters.charAt(Math.floor(Math.random() * characters.length))
      }
      return result
    },

    scrollToBottom() {
      const chatMessages = this.$refs.chatMessages
      if (chatMessages) {
        chatMessages.scrollTop = chatMessages.scrollHeight
      }
    },
    toggleThemeMenu() {
      this.showThemeMenu = !this.showThemeMenu
    },
    selectTheme(theme) {
      this.currentTheme = theme
      this.showThemeMenu = false
    },
    handleEnterPress(e) {
    if (e.shiftKey) {
      // 允许Shift+Enter换行
      const textarea = this.$refs.messageInput;
      const start = textarea.selectionStart;
      const end = textarea.selectionEnd;
      const value = textarea.value;
      
      // 在光标位置插入换行符
      this.userInput = value.substring(0, start) + '\n' + value.substring(end);
      
      // 设置新的光标位置
      this.$nextTick(() => {
        textarea.selectionStart = textarea.selectionEnd = start + 1;
        this.adjustTextareaHeight();
      });
    } else {
      this.doChat();
    }
    },
    adjustTextareaHeight() {
    const textarea = this.$refs.messageInput;
    if (!textarea) return;
    
    // 重置高度以获取正确的scrollHeight
    textarea.style.height = 'auto';
    
    // 设置最小高度
    const minHeight = 24;
    // 计算新高度，但不超过最大高度
    const newHeight = Math.max(minHeight, Math.min(textarea.scrollHeight, 150));
    textarea.style.height = newHeight + 'px';
    }
  }
}
</script>

<style scoped>
.chat-container {
  font-family: KaiTi, "楷体", STKaiti, "华文楷体", serif;
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  height: 90vh;
  display: flex;
  flex-direction: column;
  background: v-bind('currentTheme ? currentTheme.gradient : "#f5f5f5"');
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  transition: background 0.3s ease;
}

.theme-selector {
  position: absolute;
  right: 20px;
  top: 15px;
}

.theme-button {
  padding: 8px 15px;
  background: v-bind('currentTheme ? currentTheme.gradient : "#4CAF50"');
  color: rgb(113, 55, 146);
  border: 1px solid rgba(255, 255, 255, 0.3);
  border-radius: 4px;
  cursor: pointer;
  transition: background 0.3s;
  font-family: KaiTi, "楷体", STKaiti, "华文楷体", serif;
  font-size: 0.8em;
}

.theme-button:hover {
  filter: brightness(1.2);
  background: v-bind('currentTheme ? currentTheme.gradient : "#388E3C"');
}

.theme-menu {
  position: absolute;
  top: 100%;
  right: 0;
  margin-top: 5px;
  background: white;
  border-radius: 4px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  z-index: 1000;
}

.theme-item {
  padding: 10px 20px;
  cursor: pointer;
  white-space: nowrap;
  transition: background 0.3s;
  color: #333;
}

.theme-item:hover {
  background: #e0e0e0;
}
.chat-header {
  padding: 15px;
  background: v-bind('currentTheme ? currentTheme.gradient : "#4CAF50"');
  color: rgb(12, 54, 132);
  border-radius: 8px 8px 0 0;
  margin-bottom: 20px;
  position: relative;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.2);
  font-size: 1.6em;
}

.user-name {
  color: #FFD700;
  font-weight: bold;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.3);
}

.theme-button {
  padding: 8px 15px;
  background: v-bind('currentTheme ? currentTheme.gradient : "#4CAF50"');
  color: white;
  border: 1px solid rgba(255, 255, 255, 0.5);
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
  font-weight: bold;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.2);
}

.user-input-container {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-top: 10px;
  max-width: 400px;
}

.user-input-field {
  flex: 1;
  padding: 10px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-radius: 4px;
  outline: none;
  background: rgba(255, 255, 255, 0.95);
  font-size: 1em;
  transition: all 0.3s;
  color: #333;
  font-family: KaiTi, "楷体", STKaiti, "华文楷体", serif;
}

.user-input-field::placeholder {
  color: rgba(0, 0, 0, 0.5);
  font-family: KaiTi, "楷体", STKaiti, "华文楷体", serif;
}

.user-input-field:focus {
  border-color: rgba(255, 255, 255, 0.8);
  box-shadow: 0 0 5px rgba(255, 255, 255, 0.3);
}

.submit-button {
  padding: 10px 20px;
  background: v-bind('currentTheme ? currentTheme.gradient : "#4CAF50"');
  color: rgb(28, 4, 10);
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
  font-weight: bold;
  text-shadow: 1px 1px 2px rgba(30, 103, 112, 0.2);
  font-family: KaiTi, "楷体", STKaiti, "华文楷体", serif;
  font-size: large;
}

.submit-button:hover {
  filter: brightness(1.1);
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 15px;
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.message {
  display: flex;
  align-items: flex-start;
  gap: 10px;
  max-width: 80%;
}

.message.user {
  margin-left: auto;
  flex-direction: row-reverse;
}

.message.bot {
  margin-right: auto;
}
.avatar, .user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: black;
  font-weight: bold;
  background: #2196F3;
  font-size: 16px;
  line-height: 1;
}



.avatar {
  background: #4CAF50;
}

.user-avatar {
  background: #2196F3;
}

.text {
  padding: 12px;
  border-radius: 8px;
  background: white;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  width: 100%;
  text-align: justify;
}

.text :deep(think) {
  font-size: 0.9em;
  display: block;
  color: #666;
  background-color: #f9f9f9;
  padding: 8px;
  border-radius: 4px;
  margin-bottom: 8px;
}

.text :deep(div) {
  font-size: 1em;
  color: inherit;
}

.text :deep(p) {
  margin: 0.5em 0;
}

.message.user .text {
  background: #2196F3;
  color: white;
}

.chat-input {
  margin-top: 20px;
  display: flex;
  gap: 10px;
}

.message-textarea {
  flex: 1;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  outline: none;
  resize: none;
  min-height: 24px;
  max-height: 150px;
  line-height: 1.5;
  font-family: inherit;
  overflow-y: auto;
  white-space: pre-wrap;
  word-wrap: break-word;
  word-break: break-all;
}

.chat-input button {
  padding: 12px 24px;
  background: v-bind('currentTheme ? currentTheme.gradient : "#4CAF50"');
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
  align-self: flex-start;
}

.chat-input button:hover {
  filter: brightness(1.1);
}
</style>